const router = require('../config/router');
const moment = require('moment');
const redis = require('../config/redis');
const _ = require('lodash');
/**
 * 验证是否进行判断
 * @type {function(): Function}
 */
function check() {
    return async (ctx, next) => {
        const url = ctx.request.url;
        const status = verifyRoute(url);
        // 为了放行硬件，无奈之举
        if (_.includes(url, '/api/ReportStatus')) {
            await next();
        } else if (_.includes(url, '/api/BeginService')) {
            await next();
        } else if (_.includes(url, '/api/FinishService')) {
            await next();
        } else if (!status) {
            const admin = _.includes(url, '/api/admin');
            if (!admin) {
                const {
                    db,
                    user: { User }
                } = ctx;

                // 获取当前信息
                let user = await db.User.findOne({ where: { id: User.id } });
                const nowTime = Math.round(new Date() / 1000);
                const express =
                    Math.round(
                        moment()
                            .endOf('day')
                            .valueOf() / 1000
                    ) - Math.round(new Date() / 1000);
                const info = {
                    status: 1,
                    msg: User.nickName + ': It has been updated today.'
                };

                if (!user) {
                    // 如果ID被删除报错
                    ctx.errors('服务器错误');
                    return;
                }

                if (user.buyCardTime) {
                    // 检查次卡
                    const key = user.openId + user.id + 'cardKey';
                    const value = await redis.get(key);
                    if (!value) {
                        const buyCardTime = user.buyCardTime;
                        const endCardTime = user.endCardTime;
                        const day = endCardTime - buyCardTime;
                        const carDay = Math.round(nowTime - buyCardTime);
                        console.log('次卡购买时间', buyCardTime);
                        console.log('次卡已过时间', carDay);
                        if (carDay > day) {
                            user.limit = 0;
                            user.buyCardTime = null;
                            user.endCardTime = 0;
                            user.cardTimeId = 0;
                            user.save();
                        }

                        redis.set(key, JSON.stringify(info));
                        redis.expire(key, express);
                    }
                }

                if (user.memberId === 0) {
                    //会员卡id等于0略过
                    await next();
                } else {
                    //会员卡id不等于0
                    // 查看今日key是否更新
                    const key = user.openId + user.id + 'cardMember';
                    const value = await redis.get(key);
                    if (!value) {
                        // 结束开始时间
                        const buyMemberTime = user.buyMemberTime;
                        const endMemberTime = user.endMemberTime;
                        const days = endMemberTime - buyMemberTime;

                        // 更新次卡会员剩余天数,当前时间减去购买时间
                        const changeDay = Math.round(nowTime - buyMemberTime);

                        console.log('会员卡购买时间', buyMemberTime);
                        console.log('会员卡已过时间', changeDay);
                        console.log('timeout', days);

                        if (changeDay > days) {
                            user.leftDay = 0;
                            user.memberId = 0;
                            user.endMemberTime = null;
                            user.buyMemberTime = null;
                        } else {
                            const remaining = days - changeDay;
                            user.leftDay = remaining;
                            console.log('remaining', remaining);
                        }

                        redis.set(key, JSON.stringify(info));
                        redis.expire(key, express);
                        user.save();
                        await next();
                    } else {
                        await next();
                    }
                }
            } else {
                await next();
            }
        } else {
            await next();
        }
    };
}
/**
 * 过滤白名单
 * @type {function(): Function}
 */
function verifyRoute(url) {
    const status = _.includes(router, url);
    return status;
}

module.exports = check;
